package io.github.libkodi.basic_gateway.tools;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;

import io.github.libkodi.basic_gateway.annotations.Order;

public class AnnoationUtils {
	/**
	 * 排序被Order注解的类
	 * @param list 需要排序的类列表
	 */
	public static void sortByOrder(ArrayList<Class<?>> list) {
		Collections.sort(list, (a, b) -> {
			long av = 0, bv = 0;
			
			if (a.isAnnotationPresent(Order.class)) {
				av = a.getAnnotation(Order.class).value();
			}
			
			if (b.isAnnotationPresent(Order.class)) {
				bv = b.getAnnotation(Order.class).value();
			}
			
			if (av != bv) {
				return av > bv ? 1 : -1;
			} else {
				return 0;
			}
		});
	}
	
	/**
	 * 从类中查找指定注解的方法
	 * @param cls 类
	 * @param anno 目标注解
	 * @return {@link Method}
	 */
	public static Method getMethod(Class<?> cls, Class<? extends Annotation> anno) {
		Method[] methods = cls.getDeclaredMethods();
		
		for (Method method : methods) {
			if (method.isAnnotationPresent(anno)) {
				return method;
			}
		}
		
		return null;
	}
}
